<template>
    <div class="edu-page-warp">
        <div class="left-part-box">
          <div class="edu-page-title">部门层级</div>
          <div style="padding: 8px;" class="bg-white">
            <p class="tree-title">
              <span>同济大学</span>
              <el-button type="text" size="mini" @click="addRootDept(-1)" v-premit="'create_dept'">{{$t('message.add')}}</el-button>
            </p>
            <el-tree
              :data="deptTree"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span :title="node.label">{{ getLabelStr(node.label) }}</span>
                <span>
                  <el-button type="text" size="mini" @click="() => addDept(node, data)" v-premit="'create_dept'">{{$t('message.add')}}</el-button>
                  <!-- <el-button type="text" size="mini" @click="() => deleteDept(node, data)" v-premit="'delete_dept'">{{$t('message.delete')}}</el-button> -->
                </span>
              </span>
            </el-tree>
            </div>
        </div>
        <div class="right-part-box">
            <div class="edu-page-title">部门层级明细</div>
            <el-card shadow="never">
                <el-row class="pd-20px bg-white" :gutter="20">
                    <el-col :span="6">
                        <el-input v-model="queryDeptForm.deptName" placeholder="部门名称" prefix-icon="el-icon-search" @keyup.enter.native="queryDepartments"></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-button @click="queryDepartments">{{$t('message.filter')}}</el-button>
                    </el-col>
                    <!-- <el-col :span="12"> -->
                        <!-- <div class="float-right">
                            <el-button @click="deleteDepts" v-premit="'delete_dept'">{{$t('message.delete')}}</el-button> -->
                            <!-- <el-button type="primary" @click="addRootDept(-1)">{{$t('message.add')}}</el-button> -->
                        <!-- </div> -->
                    <!-- </el-col> -->
                </el-row>
                <el-row>
                <el-col>
                    <el-table :data="depts" size="mini" @selection-change="handleDeptSelectChange" stripe>
                        <el-table-column type="selection"></el-table-column>
                        <el-table-column label="代码"><template slot-scope="scope">{{scope.row.deptCode}}</template></el-table-column>
                        <el-table-column label="部门名称">
                            <template slot-scope="scope">
                              <!-- <el-tooltip class="item" effect="light" :content="scope.row.deptName" placement="top-start"> -->
                                <span :title="scope.row.deptName">{{scope.row.deptName}}</span>
                              <!-- </el-tooltip> -->
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('system.department.deptNameEn')">
                          <template slot-scope="scope">
                            <span :title="scope.row.deptName">{{scope.row.deptNameEn}}</span>
                          </template>
                        </el-table-column>
                        <!-- <el-table-column label="上级部门"><template slot-scope="scope">{{scope.row.parentDeptName}}</template></el-table-column>
                        <el-table-column label="办公地点"><template slot-scope="scope">{{scope.row.address}}</template></el-table-column>
                        <el-table-column label="联系电话"><template slot-scope="scope">{{scope.row.contactTelephone}}</template></el-table-column>
                        <el-table-column label="备注"><template slot-scope="scope">{{scope.row.description}}</template></el-table-column> -->
                        <el-table-column :label="$t('system.department.isUnderStudent')"><template slot-scope="scope">{{scope.row.isUnderStudent === "1" ? $t('system.department.have') : $t('system.department.notHave')}}</template></el-table-column>
                        <el-table-column :label="$t('system.department.isPostStudent')"><template slot-scope="scope">{{scope.row.isPostStudent === "1" ?  $t('system.department.have') : $t('system.department.notHave')}}</template></el-table-column>
                        <el-table-column :label="$t('system.department.currentState')">
                          <template slot-scope="scope">
                            <el-tag v-if="scope.row.currentState === '1'" type="success" size="mini">{{$t('system.department.enable')}}</el-tag>
                            <el-tag v-else-if="scope.row.currentState === '0'" type="danger" size="mini">{{$t('system.department.stop')}}</el-tag>
                          </template>
                          </el-table-column>
                        <el-table-column :label="$t('system.department.isCourse')"><template slot-scope="scope">{{scope.row.isCourse === "1" ?  $t('system.department.yes') : $t('system.department.no')}}</template></el-table-column>
                        <el-table-column label="是否学院">
                          <template slot-scope="scope">
                            {{scope.row.isFaculty === "1" ?  $t('system.department.yes') : $t('system.department.no')}}
                          </template>
                        </el-table-column>ssss
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" @click="editDept(scope.row)">{{$t('message.edit')}}</el-button>
                                <!-- <el-button type="text" @click="deleteDeptByRow(scope.row.deptId)" v-premit="'delete_dept'">{{$t('message.delete')}}</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handlePageNumChange"
                            :current-page="queryDeptForm.pageNum"
                            :page-sizes="[20,50,100,500,1000]"
                            :page-size="queryDeptForm.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="queryDeptForm.total" style="float: right;margin:10px 60px 0 0;">
                        </el-pagination>
                    </el-col>
                </el-row>
            </el-card>
        </div>
        <el-dialog :title="switchType === 1 ? $t('system.department.addDept') : $t('system.department.editDept')" width="42%"
				  :visible.sync="showDeptsDialog">
          <el-form :model="createDeptForm" ref="createDeptForm" label-width="80px" :rules="rules">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="上级部门">
                  <el-input v-model="createDeptForm.parentDeptName" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="代码" prop="deptCode">
                  <el-input v-model="createDeptForm.deptCode"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="部门名称" prop="deptName">
                  <el-input v-model="createDeptForm.deptName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item  :label="$t('system.department.deptNameEn')" prop="deptNameEn">
                  <el-input v-model="createDeptForm.deptNameEn"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('system.department.isUnderStudent')" prop="isUnderStudent">
                  <el-select v-model="createDeptForm.isUnderStudent" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in deptFormOption.studentOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('system.department.isPostStudent')" prop="isPostStudent">
                  <el-select v-model="createDeptForm.isPostStudent" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in deptFormOption.studentOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否学院">
                  <el-select v-model="createDeptForm.isFaculty" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in deptFormOption.isFaculty"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('system.department.isCourse')" prop="isCourse">
                  <el-select v-model="createDeptForm.isCourse" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in deptFormOption.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话">
                  <el-input v-model="createDeptForm.contactTelephone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('system.department.currentState')" prop="currentState">
                  <el-select v-model="createDeptForm.currentState" placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="item in deptFormOption.currentState"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input v-model="createDeptForm.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form> 
          <span slot="footer">
            <el-button @click="showDeptsDialog = false">{{$t('message.cancel')}}</el-button>
            <el-button v-if="switchType === 1" type="primary" @click="createDept">新增</el-button>
            <el-button v-else-if="switchType === 2" type="primary" @click="createDept">{{$t('message.submit')}}</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
import {
  findAllDeptList,
  findAllDepartmentList,
  deleteDeptList,
  addDept,
  updateDept
} from "common/src/api/user";
export default {
  name: "Departments",
  data() {
    var validateCode = (rule, value, callback) => {
      var regex = /^[\w\d]{6,10}$/;
      if (regex.test(value)) {
        callback();
      } else {
        callback(new Error("字母或数字(6~10位)"));
      }
    };
    var validateDeptName = (rule, value, callback) => {
      var regex = /^[\w\d\u4e00-\u9fa5]{4,15}$/;
      if (regex.test(value)) {
        callback();
      } else {
        callback(new Error("中文,字母或数字(4~15位)"));
      }
    };
    return {
      showDeptsDialog: false,
      switchType: 0, // 切换的类型 1：新增， 2：编辑
      queryDeptForm: {
        deptName: "",
        parentDeptId: "",
        total: 0,
        pageNum_: 1,
        pageSize_: 20
      },
      deptTree: [],
      allDepts: [],
      depts: [],
      pickedDepts: [],
      defaultProps: {
        children: "children",
        label: "deptName"
      },
      createDeptForm: {
        deptId: "",
        parentDeptName: "",
        parentDeptId: "",
        address: "",
        contactTelephone: "",
        deptName: "",
        deptNameEn: "",
        deptCode: "",
        description: "",
        isUnderStudent: "1",
        isPostStudent: "1",
        currentState: "1",
        isCourse: "1",
        isFaculty: '1'
      },
      deptFormOption: {
        options: [
          {
            value: "1",
            label: this.$t('system.department.yes')
          },
          {
            value: "0",
            label: this.$t('system.department.no')
          }
        ],
        studentOptions: [
          {
            value: "1",
            label: this.$t('system.department.have')
          },
          {
            value: "0",
            label: this.$t('system.department.notHave')
          }
        ],
        currentState: [
          {
            value: "1",
            label: this.$t('system.department.enable')
          },
          {
            value: "0",
            label: this.$t('system.department.stop')
          }
        ],
        isFaculty: [
          {
            value: '1',
            label: this.$t('system.department.yes')
          },
          {
            value: '0',
            label: this.$t('system.department.no')
          }
        ]
      },
      rules: {
        deptName: [
          {
            required: true,
            message: "请输入部门名称",
            trigger: "blur"
          }
        ],
        deptNameEn: [
          {
            required: true,
            message: this.$t("message.plsInputNameEn"),
            trigger: "blur"
          }
        ],
        deptCode: [
          {
            required: true,
            message: "请输入部门代码",
            trigger: "blur"
          },
          {
            validator: validateCode,
            trigger: "blur"
          }
        ]
      },
    };
  },
  created() {
  },
  mounted() {
    this.showDeptTree();
    this.queryDepartments();
  },
  methods: {
    getLabelStr(str) {
      if (!str) return "";
      else return str.length > 10 ? str.substring(0, 10).concat("...") : str;
    },
    handlePageNumChange(val) {
      this.queryDeptForm.pageNum_ = val;
      this.queryDepartments();
    },
    handleSizeChange(val) {
      this.queryDeptForm.pageSize_ = val;
      this.queryDepartments();
    },
    cancelCreate() {},
    createDept() {
      this.$refs.createDeptForm.validate(valid => {
        if (valid && this.switchType === 1) {
          addDept(this.createDeptForm)
            .then(res => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "添加成功."
                });
                this.showDeptsDialog = false;
                this.queryDepartments();
                this.showDeptTree();
              } else if (res.code == 300)
                this.$message({
                  type: "error",
                  message: "部门重复."
                });
              else throw res.code;
            })
            .catch(error => {
              console.log(error);
            });
        } else if (valid && this.switchType === 2) {
          updateDept(this.createDeptForm)
            .then(res => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功."
                });
                this.showDeptsDialog = false;
                this.queryDepartments();
                this.showDeptTree();
              }
              else throw res.code;
            })
            .catch(error => {
              console.log(error);
            });
        }
      });
    },
    editDept(row) {
      // 初始化createDeptForm
      this.initCreateDeptFrom();
      this.switchType = 2;
      this.showDeptsDialog = true;
      console.log(row, 'row')
      if (this.showDeptsDialog) this.createDeptForm = {
        deptId: row.deptId,
        parentDeptName: row.parentDeptName,
        parentDeptId: row.parentDeptId,
        address: row.address,
        contactTelephone: row.contactTelephone,
        deptName: row.deptName,
        deptNameEn: row.deptNameEn,
        deptCode: row.deptCode,
        description: row.description,
        isUnderStudent: row.isUnderStudent,
        isPostStudent: row.isPostStudent,
        currentState: row.currentState,
        isCourse: row.isCourse,
        isFaculty: row.isFaculty
      };
    },
    deleteDeptByRow(deptId) {
      let hasChild = this.allDepts.some((item, index) => {
        return item.parentDeptId == deptId;
      });
      if (hasChild) {
        this.$message({
          type: "warning",
          message: "该部门存在子部门, 不可删除."
        });
        return;
      }
      this.$confirm("此操作将会永久删除该部门, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(_ => {
          this._deleteDept([deptId]);
        })
        .catch(error => {
          console.log(error);
        });
    },
    deleteDept(node, data) {
      if (node.childNodes.length > 0) {
        this.$message({
          type: "warning",
          message: "该部门存在子部门, 不可删除."
        });
        return;
      }
      this.$confirm("此操作将会永久删除该部门, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(_ => {
          this._deleteDept([data.deptId]);
        })
        .catch(_ => {
          console.log("cancel");
        });
    },
    deleteDepts() {
      if (this.pickedDepts.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的部门."
        });
        return;
      }
      var hasChild = false;
      let deptIds = [];
      let allPickedDepts = this.pickedDepts;
      let all = this.allDepts;
      for (let i = 0; i < allPickedDepts.length; i++) {
        deptIds.push(allPickedDepts[i]["deptId"]);
        hasChild = all.some((ele, j) => {
          return ele.parentDeptId == allPickedDepts[i]["deptId"];
        });
        if (hasChild) {
          break;
        }
      }
      if (hasChild) {
        this.$message({
          type: "warning",
          message: "该部门存在子部门, 不可删除."
        });
        return;
      }
      this.$confirm("此操作将会永久删除该部门, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(_ => {
          this._deleteDept(deptIds);
        })
        .catch(_ => {
          console.log("cancel");
        });
    },
    _deleteDept(deptIds) {
      deleteDeptList(deptIds)
        .then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功."
            });
            this.queryDepartments();
            this.showDeptTree();
          } else if (res.code == 300)
            this.$message({
              type: "warning",
              message: "该部门已关联角色, 不可删除."
            });
          else throw res.code;
        })
        .catch(error => {
          console.log(error);
        });
    },
    addDept(node, data) {
      this.initCreateDeptFrom();
      if (!data) return;
      this.createDeptForm.parentDeptName = data.deptName;
      this.createDeptForm.parentDeptId = data.deptId;
      this.switchType = 1;
      this.showDeptsDialog = true;
    },
    initCreateDeptFrom() {
      // 初始化createDeptForm
      this.createDeptForm = {
        parentDeptName: "",
        parentDeptId: "",
        address: "",
        contactTelephone: "",
        deptName: "",
        deptNameEn: "",
        deptCode: "",
        description: "",
        isUnderStudent: "1",
        isPostStudent: "1",
        currentState: "1",
        isCourse: "1"
      };
    },
    addRootDept() {
      this.initCreateDeptFrom();
      this.createDeptForm.parentDeptName = "同济大学";
      this.createDeptForm.parentDeptId = -1;
      this.switchType = 1;
      this.showDeptsDialog = true;
    },
    handleDeptSelectChange(val) {
      this.pickedDepts = val;
    },
    queryDepartments() {
      findAllDepartmentList(this.queryDeptForm)
        .then(res => {
          if (res.code == 200) {
            this.depts = res.data.list;
            this.queryDeptForm.total = res.data.total_;
          } else throw res.code;
        });
    },
    showDeptTree() {
      findAllDepartmentList({
        pageNum_: 0,
        pageSize_: 0
      }).then(res => {
          console.log(res);
          if (res.code == 200) {
            this.deptTree = this.$utils.listToTree("deptId", "parentDeptId", res.data.list);
            this.allDepts = res.data.list;
          } else throw res.code;
        })
        .catch(error => {
          console.log(error);
        });
    },
  },
  watch: {
    showDeptsDialog: function(_old, _new) {
      if (!_new) this.$refs.createDeptForm.resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
.left-part-box,
.right-part-box {
  float: left;
  margin-right: 20px;
}
.left-part-box {
  width: 300px;
  .el-tree {
    min-height: 450px;
    max-height: 600px;
    overflow: auto;
  }
}
.right-part-box {
  width: calc(96% - 300px);
  .el-card {
    width: 100%;
    min-height: 450px;
    display: inline-block;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 4px;
  color: #3f3f3f;
}
.item-title {
  display: block;
  width: 100%;
  height: 32px;
}
.tree-title {
  margin: 0;
  line-height: 28px;
  padding-left: 8px;
  .el-button {
    float: right;
    margin-right: 4px;
  }
}
</style>
